﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PcArduinoControl
{
    /// <summary>
    /// Keeps track of last 200 bytes of data sent and Received
    /// </summary>
    class SerialLog
    {
        enum SentReceived
        {
            Sent,
            Received
        }

		Log mLog;
		Tuple<DateTime, Direction, byte>[] mSerialLog = new Tuple<DateTime, Direction, byte>[200];
        int mMostRecentIndex;

        public SerialLog(Log log)
        {
			mLog = log;
            mMostRecentIndex = 0;
        }

        public void LogSent(params byte[] bytes)
        {
			lock (mSerialLog)
			{
				for (int i = 0; i < bytes.Length; i++)
				{
					mMostRecentIndex = (mMostRecentIndex + 1) % mSerialLog.Length;
					mSerialLog[mMostRecentIndex] = Tuple.Create(DateTime.Now, Direction.PcToArduino, bytes[i]);
				}
			}
        }

        public void LogReceived(params byte[] bytes)
        {
			lock (mSerialLog)
			{
				for (int i = 0; i < bytes.Length; i++)
				{
					mMostRecentIndex = (mMostRecentIndex + 1) % mSerialLog.Length;
					mSerialLog[mMostRecentIndex] = Tuple.Create(DateTime.Now, Direction.ArduinoToPc, bytes[i]);
				}
			}
        }

        public void WriteToMainLog()
        {
			lock (mSerialLog)
			{
				mLog.WriteLine("Serial Log {");
				int i = (mMostRecentIndex + 1) % mSerialLog.Length;
				while (true)
				{
					if (mSerialLog[i] != null)
					{
						mLog.WriteLine
						(
							mSerialLog[i].Item1.ToString("yyyy-MM-dd HH:mm:ss.fff") + ", " +
							mSerialLog[i].Item2.ToString() + ", " +
							string.Format("{0:X}", mSerialLog[i].Item3)
						);
						mSerialLog[i] = null;
					}
					i = (i + 1) % mSerialLog.Length;

					if (i == (mMostRecentIndex + 1) % mSerialLog.Length)
						break;
				}
				mLog.WriteLine("} End of a Serial Log");
			}
        }
    }
}
